/*
This file is part of buco.  
Copyright (c) 2012 Christopher Pawelzik <christopher@cpawelzik.com>

Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
*/ 
package buco.core.internal;

import java.util.*;

/*
 *  Parses OSGi Header values according to the common header syntax
 *  defined in OSGi R4 Core Specification, p. 29 
 */ 
public final class HeaderParser {
	
	public static List<HeaderElement> parseHeaderValue(String header) {
		ArrayList<HeaderElement> list = new ArrayList<HeaderElement>(); 
		String[] elements = splitQuotedString(header);
		for(String element : elements)  {
			list.add(parseHeaderElement(element)); 
		}
		return list; 
	}
	
	/*
	 * 
	 */
	private static HeaderElement parseHeaderElement(String header) {		
		String[] elements = splitQuotedString(header, ';');
		HeaderElement headerElement = new HeaderElement(elements[0]);
		if(elements.length > 1) {
			// Element has attributes or drectives 									
			for(int i=1; i < elements.length; i++) {
				Attribute attribute = parseAttribute(elements[i]); 
				headerElement.addAttribute(attribute); 
			}
		}
		
		return headerElement; 
	}
	
	private static Attribute parseAttribute(String attribStr) {
		String[] pair = splitQuotedString(attribStr, '=');
		String key = pair[0].trim();
		String value = pair[1].trim();
						
		// Remove quotes
		if(value.startsWith("\"") && value.endsWith("\"")) {
			value = value.substring(1, value.length()-1);
		}
		
		// Handle directive 
		if(key.endsWith(":")) {
			return new Directive(key.substring(0, key.length()-1).trim(), value); 
		}
		
		return new Attribute(key, value); 
	}
	
		
	/*
	 * Input might be: 
	 * osgi.org.package1;version="2.0,3",osgi.org.package2;version="1.0,2"
	 * Output: 
	 * 	osgi.org.package1;version="2.0,3"
	 *  osgi.org.package2;version="1.0,2"
	 */
	public static String[] splitQuotedString(String input, char delimiter)  {
		ArrayList<String> list = new ArrayList<String>(); 
		boolean isQuotedState = false; 
		int start = 0; 		
		
		for(int i=0; i < input.length(); i++) {
			char c = input.charAt(i);
			if(c == '"')  {
				isQuotedState = !isQuotedState; 
			} 
			else if(c == delimiter && !isQuotedState) {
				list.add(input.substring(start, i).trim()); 
				start = i + 1; 
			}			
		}
				
		if(input.charAt(input.length() - 1) != delimiter) {
			// one element left 
			list.add(input.substring(start, input.length()));
		}
		
		return list.toArray(new String[list.size()]);
	}
	
	/*
	 * 
	 */
	public static String[] splitQuotedString(String input)  {
		return splitQuotedString(input, ','); 
	}
}
